<!-- 更多功能 –修改服务费 - 弹窗组件 -->
<template>
  <CustomDialog v-model:visible="dialogVisible" top="15vh" width="40%">
    <div class="edit-service-charge-dialog">
      <div class="title">修改服务费</div>
      <div class="form-item">
        <div class="input-box">
          <div class="input-wrapper">
            <input
              class="input"
              v-model.trim="serviceFee"
              type="text"
              placeholder="请输入服务费"
              @focus="handleInputFocus"
              @input="handleInput"
              @keydown="handleKeyDown"
            />
            <img
              class="clear-icon"
              src="@/assets/images/home/input-clear.png"
              alt=""
              @click="handleClearInput"
              v-if="serviceFee"
            />
          </div>
        </div>
      </div>
      <!-- 数字键盘组件 -->
      <NumberKeyboard
        v-model:keyword="serviceFee"
        @onInputKeyboard="onInputKeyboard"
        @onCancel="handleCancel"
        @onConfirm="handleConfirm"
        :loading="loading"
      />
    </div>
  </CustomDialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import NumberKeyboard from '@/components/NumberKeyboard/Index.vue'
import { deskOrderEditServiceMoney } from '@/api/desktop'

interface Props {
  modelValue: boolean
  deskDetail?: any
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  deskDetail: null
})

const emit = defineEmits<Emits>()

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
})

// 当前桌台详情
const currentDeskDetail = computed(() => props.deskDetail)

// 服务费
const serviceFee = ref('')

// 加载状态
const loading = ref(false)

// 清空输入框
const handleClearInput = () => {
  serviceFee.value = ''
}

// 接收数字键盘传过来的关键词
const onInputKeyboard = (val: string) => {
  serviceFee.value = val
}

// 处理输入框获取焦点
const handleInputFocus = (event: FocusEvent) => {
  // 当输入框获取焦点时，不做特殊处理
  // 用户可以通过数字键盘或直接输入
  const inputElement = event.target as HTMLInputElement
  inputElement.select() // 选中所有文本，方便用户直接输入
}

// 处理输入事件，确保只能输入数字和小数点
const handleInput = (event: Event) => {
  const inputElement = event.target as HTMLInputElement
  const value = inputElement.value

  // 使用正则表达式验证输入是否为有效的数字格式
  // 允许数字和一个小数点
  const validInput = /^[0-9]*\.?[0-9]*$/.test(value)

  if (!validInput) {
    // 如果输入无效，恢复到上一个有效值
    serviceFee.value = serviceFee.value.replace(/[^0-9.]/g, '')
    return
  }

  // 限制只能有一个小数点
  const pointCount = (value.match(/\./g) || []).length
  if (pointCount > 1) {
    // 如果有多个小数点，保留第一个小数点
    const parts = value.split('.')
    serviceFee.value = parts[0] + '.' + parts.slice(1).join('')
    return
  }

  // 限制最多两位小数
  if (value.includes('.')) {
    const parts = value.split('.')
    if (parts[1].length > 2) {
      serviceFee.value = parts[0] + '.' + parts[1].substring(0, 2)
      return
    }
  }

  // 不限制最大值
}

// 处理键盘按下事件
const handleKeyDown = (event: KeyboardEvent) => {
  // 如果按下回车键，则触发确认操作
  if (event.key === 'Enter') {
    event.preventDefault()
    handleConfirm()
  }
}

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false
}

// 确认操作
const handleConfirm = async () => {
  if (!serviceFee.value) {
    ElMessage.warning('请输入服务费')
    return
  }

  const fee = parseFloat(serviceFee.value)

  loading.value = true
  try {
    const res = await deskOrderEditServiceMoney({
      record_id: currentDeskDetail.value.id,
      service_money: fee // 使用与旧项目一致的参数名
    })

    if (res.status === 200) {
      ElMessage.success('修改服务费成功')
      // 通知父组件刷新数据
      emit('success')
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('修改服务费失败:', error)
    ElMessage.error('修改服务费失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.edit-service-charge-dialog {
  padding: 20px;

  .title {
    font-size: 20px;
    font-family:
      PingFang SC,
      PingFang SC-Bold;
    font-weight: 700;
    text-align: center;
    color: #333333;
    margin-bottom: 20px;
  }

  .form-item {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
  }

  .input-box {
    width: 100%;
    max-width: 488px;
    display: flex;
    align-items: center;
    margin: 0 auto;
  }

  .input-wrapper {
    flex: 1;
    height: 48px;
    background: #ffffff;
    border: 1px solid #d2d2d2;
    border-radius: 12px;
    box-sizing: border-box;
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .input {
    width: 100%;
    font-size: 14px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    text-align: left;
    color: #333333;
    outline: none;
    border: none;
  }

  .clear-icon {
    flex-shrink: 0;
    width: 24px;
    height: 24px;
    cursor: pointer;
  }

  .unit {
    margin-left: 10px;
    font-weight: bold;
    font-size: 16px;
  }
}
</style>
